<!DOCTYPE html>
<html lang="zh_CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>JS 沙箱(快照沙箱) - 基于类</title>
  </head>
  <body>
    <script>
      // 此方法次在一个问题，如果是多个子应用不能使用这种方式
      // 多应用可以使用proxy实现
      class SnapshotSandbox {
        constructor() {
          this.proxy = window
          this.modifyPropsMap = {} // 记住在window上的修改
          this.active()
        }
        active() {
          this.windowSnapshot = {} //拍照
          for (const prop in window) {
            if (window.hasOwnProperty(prop)) {
              this.windowSnapshot[prop] = window[prop]
            }
          }
          Object.keys(this.modifyPropsMap).forEach((p) => {
            window[p] = this.modifyPropsMap[p]
          })
        }
        inactive() {
          for (const prop in window) {
            if (window.hasOwnProperty(prop)) {
              if (window[prop] !== this.windowSnapshot[prop]) {
                this.modifyPropsMap[prop] = window[prop]
                window[prop] = this.windowSnapshot[prop]
              }
            }
          }
        }
      }
      let sandbox = new SnapshotSandbox()
      ;((window) => {
        window.a = 1
        window.b = 2
        console.log(window.a, window.b)
        sandbox.inactive()
        console.log(window.a, window.b)
        sandbox.active()
        console.log(window.a, window.b)
      })(sandbox.proxy)
    </script>
  </body>
</html>
